#include	"Mouse.h"
#include	<Window/Window.h>
#include	<windows.h>
#include	<gl/gl.h>
#include	<OpenGL/Helper.h>
#include	<Textures/ImageTGA.h>
#include	<Textures/Texture.h>
#include	<assert.h>

Mouse::Mouse(Window * window, const std::string & texture, bool visible, const Vector2i & windowSize)
	:	IControl()
	,	m_window(window)
	,	m_texture(0)
	,	m_windowSize(windowSize)
	,	m_hitPoint(0, 0)
//	,	m_position(0, 0)
	,	m_visible(visible)
{
	ImageTGA img(texture.c_str());
	m_texture = new Texture(img);
	img.Cleanup();
}

Mouse::~Mouse()
{
	m_texture->Destroy();
}

void Mouse::update(double delay)
{
	(void)delay;
	/*m_position = Vector2i(
			int(float(m_window->MouseCursor()[0] * m_windowSize[0]) / m_window->Size()[0]),
			int(float(m_window->MouseCursor()[1] * m_windowSize[1]) / m_window->Size()[1])
		);// */
}

void Mouse::render() const
{
	if(m_visible)
	{
		assert(m_window != 0);
		glhPushOrtho(m_windowSize);
			glPushAttrib(GL_CURRENT_BIT  | GL_ENABLE_BIT);
				glEnable(GL_TEXTURE_2D);
				glEnable(GL_COLOR_MATERIAL);
				glEnable(GL_BLEND);
				Vector2i m_position = getPosition();
				Vector2i pos(m_position[0] - m_hitPoint[0], m_windowSize[1] - m_position[1] + m_hitPoint[1]);
				glBindTexture(GL_TEXTURE_2D, m_texture->Name());
				glBegin(GL_QUADS);
					glTexCoord2f(0.0f, 1.0f);
					glVertex3i(pos[0], pos[1], 0);
					glTexCoord2f(0.0f, 0.0f);
					glVertex3i(pos[0], pos[1] - m_texture->GetSize()[1], 0);
					glTexCoord2f(1.0f, 0.0f);
					glVertex3i(pos[0] + m_texture->GetSize()[0], pos[1] - m_texture->GetSize()[1], 0);
					glTexCoord2f(1.0f, 1.0f);
					glVertex3i(pos[0] + m_texture->GetSize()[0], pos[1], 0);
				glEnd();
			glPopAttrib();
		glhPopOrtho();
	}
}

//const Vector2i & Mouse::getPosition() const
Vector2i Mouse::getPosition() const
{
	return Vector2i(
			int(float(m_window->MouseCursor()[0] * m_windowSize[0]) / m_window->Size()[0]),
			int(float(m_window->MouseCursor()[1] * m_windowSize[1]) / m_window->Size()[1])
		);// */
	//return m_position;
}

bool Mouse::getVisible() const
{
	return m_visible;
}

void Mouse::setVisible(bool visible)
{
	m_visible = visible;
}

const Vector2i & Mouse::getWindowSize() const
{
	return m_windowSize;
}

